﻿using mozhi.smarterp.Finance.Files.Services;
using Mozhi.Abp.Core.Offices.Excels;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;

namespace mozhi.smarterp.Finance.Ieps.Import
{
    public class ImportHandlerBase<TData> : IImportHandler
    {
        protected IServiceProvider _serviceProvider;

        protected FileManager _fileManager;

        public ImportHandlerBase(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;

            _fileManager = _serviceProvider.GetService(typeof(FileManager)) as FileManager;
        }

        public virtual async Task<ImportResultDto> HandleImportData(Guid fileId)
        {
            return new ImportResultDto();
        }

        public async Task<List<TData>> GetImportData(string moduleCode, Guid fileId)
        {
            var fileResult = await _fileManager.DownloadFileAsync(fileId);

            if (fileResult == null)
                throw new UserFriendlyException($"文件:{fileId}不存在", "100000");

            var stream = fileResult.Item1;

            var ds = GetDataTable(stream);

            if (ds.Tables.Count == 0)
                throw new BusinessException("100000", "没有转换成功的数据");

            var datas = ConvertToData(ds);

            return datas;
        }


        #region
        private DataSet GetDataTable(Stream stream)
        {
            var excelHandler = ExcelHandlerFactory.Instance("npio");

            DataSet ds = excelHandler.GetDataSet(stream);

            return ds;
        }


        protected virtual List<TData> ConvertToData(DataSet ds)
        {
            return default(List<TData>);
        }

        protected virtual bool GetBooleanValue(string value)
        {
            if(value=="是" || value=="Y" || value=="y")
                return true;

            if (value == "否" || value == "N" || value == "n")
                return false;

            return false;
        }

        #endregion
    }
}
